let datas;
// let tempId;
let templateId;
let template_input;
$(function () {

    init_template()
    if (templateId !== undefined) {
        load_template_data(templateId);
    }

    //选择模板
    template_input.change(function () {
        let value = $(this).val();
        load_template_data(value);
        if ("true" === $('#status').val()) {
            init_send();
        }
    });

})
let last = null;

function init_template() {
    let t_first = $('#temp-menu').children().first();
    t_first.addClass('active selected');
    templateId = t_first.attr('data-value');
    let default_text = $('#default-text');
    let text = t_first.find('span').text()
    template_input = $('#templateId');
    default_text.attr("data-value", templateId);
    default_text.html(text);

    template_input.val(templateId);
}

function load_template_data(val) {
    let thisLoad = load();
    $.get({
        url: '/produce/getTemplate',
        data: {
            "templateId": val,
            "workOrderNumber": $('#workOrderNumber').val()
        },
        beforeSend: function () {
            layer.close(loading);
        },
        success: function (result) {
            if (result.status === 200) {
                datas = result.data;
                //tempId = datas.leaveOneTemplateId;
                data_encapsulation(result.data);
                layer.close(thisLoad);
            } else {
                layer.close(thisLoad);
            }
        }
    })
}

//进入修改记录查看页
$('#view-modify-record').click(function () {
    $.get({
        url: '/index/check/checkMrdPage',
        success: function (result) {
            if (result.status === 200) {
                window.location.href = ("/index/page/mrdPage/" + $('#workOrderNumber').val());
            }
        }
    })
});

//数据封装
let lastLength = 0;
let tailTr;

function data_encapsulation(data) {
    loading = load();
    let hl = parseInt(Object.keys(data.heads).length);
    let threeLength = data.leaveThreeTemplateName.length;
    let titleLength = Math.max(hl, threeLength);

    let title = $('#title');
    //   let body = $('tbody');
    // newTr = "";
    title.text(data.leaveOneTemplateName);
    title.attr("colSpan", titleLength);
    let tc = $('#myTable thead').children();
    let sc = tc.eq(3);

    let content = "";

    $.each(data.leaveTwoTemplateName, function (key, values) {
        content += "<td colspan='" + values + "'>" + key + "</td>"
    });
    sc.html(content);

    content = "";
    let st = tc.eq(4);
    $.each(data.leaveThreeTemplateName, function (index, item) {
        content += "<td colspan='1'>" + item + "</td>";
    });
    st.html(content);

    let ft = tc.eq(1);
    let tt = tc.eq(2);
    let ll = titleLength;
    let head_span = parseInt(ll / hl);
    let last_head_span = Math.max(1, parseInt(ll % hl) + head_span);
    let head_html = "";
    let head_data = "";
    let incr = 0;
    $.each(data.heads, function (key, value) {
        if (++incr === hl) {
            head_html += "<td colspan='" + last_head_span + "'>" + key + "</td>";
            head_data += "<td colspan='" + last_head_span + "' id='soft-version'>" + value + "</td>";
        } else {
            head_data += "<td colspan='" + head_span + "'>" + value + "</td>";
            head_html += "<td colspan='" + head_span + "'>" + key + "</td>";
        }
    });
    ft.html(head_html);
    tt.html(head_data);
    // let soft_version = $("#soft-version");
    // if (verify_soft_version(soft_version.text())) {
    //     soft_version.attr("contenteditable", true);
    // }
    let fields = data.fieldName;
    for (let i = 1; i <= threeLength; i++) {
        tailTr += "<td class='" + fields[i] + "' colspan='1'></td>";
    }
    tailTr += "</tr>";

    //将下发数据封装到 tbody
    packageBody(data.body);
    if (hl > threeLength) {
        let lastTd = st.children().last();
        let twoLastTd = sc.children().last();
        let tdLength = parseInt(lastTd.attr('colspan'));
        let len = hl - threeLength;
        lastLength = tdLength + len;
        lastTd.attr('colspan', lastLength);
        twoLastTd.attr('colspan', lastLength);
        last_processor(threeLength);
    }
}


function last_processor(dataLength) {
    let tbody = $('#myTable tbody');
    let data = tbody.children().not(':first');
    let head_length = parseInt($('#myTable thead').children().eq(1).children().length);
    if (dataLength >= head_length) {
        return;
    }
    $.each(data, function () {
        $(this).children().last().attr('colspan', lastLength);
    })
}

let temp_data;
let temp_tar;
let temp_field;
let temp_id;

function packageBody(body) {
    if (body.length > 0) {
        disabled_template();
    }
    //将下发数据封装到 tbody
    let tbody = $('#myTable tbody');
    tbody.children().not(':first').remove();
    let tbody_content = "";
    $('#total').text("已生产" + body.length + "台");
    let field = datas.fieldName;
    let i;
    $.each(body, function (index, item) {
        tbody_content += "<tr>";
        i = 0;
        $.each(item, function (index, value) {
            if (index === "id") {
                tbody_content += "<td class='hide identity " + field[i] + "' colspan='1'>" + value + "</td>";
            } else {
                tbody_content += "<td class='" + field[i] + "' colspan='1'>" + value + "</td>";
            }
            i++;
        });
        tbody_content += "</tr>";
    });
    tbody.append(tbody_content);

    let td = tbody.find("td");
    if ("true" === $('#status').val()) {
        td.blur(function () {
            send($(this));
        });
        td.prop("contenteditable", true);
    }
}

$(document).on('click', '#myTable tbody td', function () {
    let input = $('#content');
    // //清空文本域数据
    // input.val("");
    let cur;
    cur = $(this);
    temp_data = cur.text();
    temp_tar = cur;
    input.val(cur.text());
    cur.keyup(function () {
        input.val(cur.text());
    });
    input.keyup(function () {
        cur.text($(this).val());
    });
});

$('#newTrBtn').click(function () {
    add_send();
});

function add_line(id, count, templateId, workOrderNumber) {
    if ($('#workOrderNumber').val() === workOrderNumber && $('#templateId').val() !== templateId) {
        load_template_data(templateId);
        load_template_list(workOrderNumber);
    }
    $('#total').text("已生产" + count + "台");
    let newTr;
    newTr = "<tr class='m-content'><td class='hide identity id'>" + id + "</td>";

    newTr += tailTr;

    let tbody = $('#myTable tbody');
    tbody.append(newTr);
    let tr = tbody.children().last();
    let td = tr.children('td')
    td.prop("contenteditable", true);
    let lastTd = tr.children().last();
    let curLength = parseInt(lastTd.attr('colspan'));
    let len = Math.max(curLength, lastLength);
    lastTd.attr('colspan', len);
    td.blur(function () {
        send($(this));
    });
}

function load_template_list(workOrderNumber) {
    $.get({
        url: '/index/loadTemplateList/' + workOrderNumber,
        beforeSend: function () {
            layer.close(loading);
        },
        success: function (result) {
            if (result.status === 200) {
                package_template_menu(result.data, $('#temp-menu'));
                init_template()
                disabled_template();
            }
        }
    })
}


$('#remTrBtn').click(function () {
    let trs = $('#myTable tbody tr:not(:first)').length;
    if (trs === 0) {
        return;
    }
    r_send();
})

//显示异常上报模态窗
$('#report').click(function () {
    $('.ui.modal.report-exception').modal({
        closable: false
    }).modal("show");
});

//清除异常文本域信息
$('.ui.clear-exception-info.button').click(function () {
    $('#report-form').form('clear');
});
//异常信息 表单验证 productInfo
$('#report-form').form({
    inline: true,
    on: 'submit',
    keyboardShortcuts: false,
    fields: {
        exceptionInfo: {
            identifier: 'exceptionInfo',
            rules: [
                {
                    type: 'empty',
                    prompt: "异常信息不能为空"
                }
            ]
        },
        serialNumber: {
            identifier: 'serialNumber',
            rules: [
                {
                    type: 'empty',
                    prompt: "产品序号不能为空"
                }
            ]
        },
        productNumber: {
            identifier: 'productNumber',
            rules: [
                {
                    type: 'empty',
                    prompt: "请填写产品型号"
                }
            ]
        },
        productCode: {
            identifier: 'productCode',
            rules: [
                {
                    type: 'empty',
                    prompt: "请填写产品编码"
                }
            ]
        }
    },
    onSuccess: function () {
        report_abnormal_information();
    }
})

//异常信息提交上报
function report_abnormal_information() {
    let formData = new FormData();
    let fileUpload = $("#report-file")[0].files[0];
    formData.append('file', fileUpload)
    formData.append('exceptionReportBean', JSON.stringify({
        "serialNumber": $('#serialNumber').val(),
        "productNumber": $('#productNumber').val(),
        "productCode": $('#productCode').val(),
        "accidentDetails": $('#exceptionInfo').val(),
        "workOrderNumber": $('#workOrderNumber').val()
    }));
    $.post({
        url: '/produce/reportAbnormalInformation',
        contentType: false,
        cache: false,
        processData: false,
        dataType: "json",
        data: formData,
        success: function (result) {
            if (result.status === 200) {
                $('.ui.modal.report-exception').modal('hide');
                $('#report-form').form("reset");
                success(result.msg);
            }
        }
    })
}

$('#export').click(function () {
    if (!($('#title').text() !== "" && $('#myTable tbody tr:not(:first)').length !== 0)) {
        failure("没有数据可以导出")
        return;
    }
    let workOrderNumber = $('#workOrderNumber').val();
    $("#myTable").table2excel({
        // 不被导出的表格行的CSS class类
        exclude: ".identity",
        // 导出的Excel文档的名称
        name: "工单-" + workOrderNumber + "-" + new Date().getTime(),
        // Excel文件的名称
        filename: "工单-" + workOrderNumber + "-" + new Date().getTime(),
        bootstrap: false
    });
})

//发起完工
$(document).one('click', '#completion', function () {
    let workOrderNumber = $("#workOrderNumber").val();
    let templateId = $('#templateId').val();
    if (verify_work_order_number(workOrderNumber)) {
        failure("非法工单")
        return;
    }
    $.post({
        url: '/produce/initiateCompletion',
        data: {
            "workOrderNumber": workOrderNumber,
            "templateId": templateId,
        },
        success: function (result) {
            if (result.status === 200) {
                success(result.msg);
            }
        }
    })
})

$('#view-exception').click(function () {
    load_pending_exception_info()
    $('#exception-data').show(200);
    $('#template-data').hide();
});

$('.view-data').click(function () {
    $('#exception-data').hide();
    $('#template-data').show();
})

function load_pending_exception_info() {
    let workOrderNumber = $("#workOrderNumber").val();
    if (verify_work_order_number(workOrderNumber)) {
        failure("非法工单")
        return;
    }
    $.get({
        url: '/plan/getAllPendingExceptionInfo',
        data: {
            "workOrderNumber": workOrderNumber,
        },
        success: function (result) {
            if (result.status === 200) {
                package_pending_exception_info(result.data, $('#pending-table tbody'));
            }
        }
    })
}

function package_pending_exception_info(data, target) {
    if (data.length < 1) {
        let head = $('#pending-table thead');
        target.html("<tr><td colspan='" + head.children().children().length + "'><h2 style='font: italic 2em Georgia, serif;margin: 0 50px;'>no result</h2></td></tr>");
        return;
    }
    target.empty();
    let content;
    $.each(data, function (index, item) {
        content = "<tr>" +
            "<td class='hide exc-id'>" + item.id + "</td>" +
            "<td>" + item.serialNumber + "</td>" +
            "<td>" + item.productNumber + "</td>" +
            "<td>" + item.productCode + "</td>" +
            "<td class='accident-details hide' style='width: 100px!important;'>" + item.accidentDetails + "</td>" +
            "<td>" + item.reporter + "</td>" +
            "<td>" + item.reporterDate + "</td>" +
            "<td>" + item.status + "</td>" +
            "<td>" +
            "                <div class='ui dropdown item'>" +
            "                    More" +
            "                    <i class='dropdown icon'></i>" +
            "                    <div class='menu'>" +
            "<a class='item  view-accident-details'><i class='eye icon'></i>查看异常</>" +
            "<a class='item  sub-solution' onclick='sub_inti(" + item.id + ")'><i class='edit outline icon'></i>提交方案</a>" +
            "<a class='item  transfer-craft'><i class='heartbeat icon'></i>委托至工艺</a>" +
            "<a class='item  major-report'><i class='dolly icon'></i>重大异常上报</a>" +
            "                    </div>" +
            "                </div>" +
            "</td>" +
            "</tr>";
        target.append(content);
    });
    $('.ui.dropdown').dropdown({
        on: 'click'
    });
}

$(document).on('click', '.view-accident-details', function () {
    let mes = $(this).parents('td').siblings('.accident-details').text();
    $('#exception-details').text(mes);
    $('#download-ex-file').attr("data-value", $(this).parents('td').siblings('.exc-id').text())
    $('.ui.modal.view-exception-modal').modal({
        closable: false
    }).modal("show");
});

function sub_inti(val) {
    set_id(val);
    open_modal();
}

function set_id(val) {
    $('#exception-id').val(val);
}

function open_modal() {
    $('.ui.modal.handle-modal').modal({
        closable: false
    }).modal("show");
    $('#sub-solution-btn').removeClass("disabled");
}

$('#solution-form').form({
    inline: true,
    on: "submit",
    keyboardShortcuts: false,
    fields: {
        "treatment-plan": {
            identifier: "treatment-plan",
            rules: [
                {
                    type: "empty",
                    prompt: "请填写处理方案"
                }
            ]
        }
        // ,
        // "check": {
        //     identifier: "checkT",
        //     rules: [
        //         {
        //             type: "checked",
        //             prompt: "请选择任意一项"
        //         }
        //     ]
        // }
    },
    onSuccess: function () {
        $('#sub-solution-btn').addClass("disabled");
        submit_proposal();
    }
});

function submit_proposal() {
    let program = $('#treatment-plan').val();
    let id = $('#exception-id').val();
    let file = $("#dix-file")[0].files[0];
    //  let check = $('input[name=checkT]:checked').val();
    let workOrderNumber = $('#workOrderNumber').val();
    let formData = new FormData();
    formData.append("id", id);
    formData.append("program", program);
    formData.append("file", file);
    //  formData.append("isMajor", check);
    formData.append("workOrderNumber", workOrderNumber)
    $.post({
        url: '/plan/exceptionWorkOrderHandling',
        data: formData,
        cache: false,
        processData: false,
        dataType: "json",
        contentType: false,
        success: function (result) {
            if (result.status === 200) {
                $('.ui.modal.handle-modal').modal('hide');
                success(result.msg);
                load_pending_exception_info();
            }
        }
    })
}

$('.pending-exception').click(function () {
    $("#pending").show(100);
    $('#confirmed').hide(100);
    $('#finished').hide(100);
    load_pending_exception_info();
});

$('.pending-sure').click(function () {
    $("#pending").hide(100);
    $('#confirmed').show(100);
    $('#finished').hide(100);
    load_pending_sure();
})

$('.exception-history').click(function () {
    $("#pending").hide(100);
    $('#confirmed').hide(100);
    $('#finished').show(100);
    load_finished_exception_info()
});


function load_pending_sure() {
    let url = '/plan/getAllConfirmedExceptionInfo';
    let tail = "<a class='item view-result '><i class='chess queen icon'></i>执行结果</a><a class='item sure-plan'><i class='chess knight icon'></i>最终确认</a>";
    load_exception_info(url, tail);
}

$('.pending-execute').click(function () {
    $("#pending").hide(100);
    $('#confirmed').show(100);
    $('#finished').hide(100);
    load_pending_exe();
})

function load_pending_exe() {
    let url = '/plan/getAllPendingExeExceptionInfo';
    let tail = "<a class='item exe-plan'><i class='quidditch icon'></i>执行方案</a>";
    load_exception_info(url, tail);
}

function load_exception_info(url, tail) {
    let workOrderNumber = $("#workOrderNumber").val();
    if (verify_work_order_number(workOrderNumber)) {
        failure("非法工单")
        return;
    }
    $.get({
        url: url,
        data: {
            "workOrderNumber": workOrderNumber
        },
        success: function (result) {
            if (result.status === 200) {
                package_confirmed_exception_info(result.data, $('#confirmed-table tbody'), tail)
            }
        }
    })
}

function package_confirmed_exception_info(data, target, tail) {
    if (data.length < 1) {
        let head = $('#confirmed-table thead');
        target.html("<tr><td colspan='" + head.children().children().length + "'><h2 style='font: italic 2em Georgia, serif;margin: 0 50px;'>no result</h2></td></tr>");
        return;
    }
    target.empty();
    let content;
    $.each(data, function (index, item) {
        content = "<tr>" +
            "<td class='hide exc-id'>" + item.id + "</td>" +
            "<td>" + item.serialNumber + "</td>" +
            "<td>" + item.productNumber + "</td>" +
            "<td>" + item.productCode + "</td>" +
            "<td class='accident-details hide' style='width: 100px!important;'>" + item.accidentDetails + "</td>" +
            "<td>" + item.reporter + "</td>" +
            "<td>" + item.reporterDate + "</td>" +
            "<td class='treatment-details hide'>" + item.treatmentPlan + "</td>" +
            "<td>" + item.closedLoopPeople + "</td>" +
            "<td>" + item.closedLoopPeopleDate + "</td>" +
            "<td class='execute-details hide'>" + item.executeResult + "</td>" +
            "<td>" + item.status + "</td>" +
            "<td>" +
            "                <div class='ui dropdown item'>" +
            "                    More" +
            "                    <i class='dropdown icon'></i>" +
            "                    <div class='menu'>" +
            tail +
            "<a class='item view-accident-details '><i class='paw icon'></i>查看异常</a>" +
            "<a class='item view-treatment-plan '><i class='eye icon'></i>查看方案</a>" +
            "                    </div>" +
            "                </div>" +
            "</td>" +
            "</tr>";
        target.append(content);
    });
    $('.ui.dropdown').dropdown({
        on: 'click'
    });
}

$(document).on('click', '.view-treatment-plan', function () {
    let mes = $(this).parents('td').siblings('.treatment-details').text();
    $('#plan-details').text(mes);
    $('#dix-download').attr("data-value", $(this).parents('td').siblings('.exc-id').text())
    $('.ui.modal.view-treatment-modal').modal({
        closable: false
    }).modal("show");
});
//view-result
$(document).on('click', '.view-result', function () {
    let mes = $(this).parents('td').siblings('.execute-details').text();
    $('#execute-details').text(mes);
    $('.ui.modal.view-execute-modal').modal({
        closable: false
    }).modal("show");
});
let r_e_t;
$(document).on('click', '.exe-plan', function () {
    $('.layui-layer-btn0').removeClass('end');
    $('#sub-execute-btn').attr("data-value", $(this).parents('td').siblings('.exc-id').text());
    r_e_t = $(this);
    layer.confirm('确认要执行吗?', {
        btn: ['确定', '取消'],
        icon: 3,
        title: '提示',
        shade: [0.6, '#ffffff', true]
    }, function (index) {
        $('.layui-layer-btn0').addClass('end');
        sub_exe_result();
        layer.close(index);
    });
});

$(document).on('click', '.major-report', function () {
    let id=$(this).parents('td').siblings('.exc-id').text()
    $('.layui-layer-btn0').removeClass('end');
    layer.confirm('确定为重大异常吗?', {
        btn: ['确定', '取消'],
        icon: 3,
        title: '提示',
        shade: [0.6, '#ffffff', true]
    }, function (index) {
        $('.layui-layer-btn0').addClass('end');
        report_major_exception(id);
        layer.close(index);
    });
})

$(document).on('click', '.transfer-craft', function () {
    $('.layui-layer-btn0').removeClass('end');
    let id = $(this).parents('td').siblings('.exc-id').text();
    layer.confirm('确定要委托给工艺吗?', {
        btn: ['确定', '取消'],
        icon: 3,
        title: '提示',
        shade: [0.6, '#ffffff', true]
    }, function (index) {
        $('.layui-layer-btn0').addClass('end');
        transfer_to_craft(id);
        layer.close(index);
    });
})

function report_major_exception(id) {
    let workOrderNumber = $('#workOrderNumber').val();
    $.get({
        url: '/plan/reportAMajorException/' + workOrderNumber+"/"+id,
        success: function (result) {
            if (result.status === 200) {
                success(result.msg);
            }
        }
    })
}

function transfer_to_craft(id) {
    $.get({
        url: '/plan/transfer/' + id,
        success: function (result) {
            if (result.status === 200) {
                success(result.msg);
            }
        }
    })
}


$('#download-ex-file').click(function () {
    let id = $(this).attr("data-value");
    let suffix = get_file_suffix(id, 1);
    if (suffix.length === 0) {
        return;
    }
    let url = "/plan/download/" + id + "/1";
    let fileName = "异常信息附件-" + new Date().getTime() + suffix;
    download(fileName, url);
})

$('#dix-download').click(function () {
    let id = $(this).attr("data-value");
    let suffix = get_file_suffix(id, 2);
    if (suffix.length === 0) {
        return;
    }
    let url = "/plan/download/" + id + "/2";
    let fileName = "异常处理附件-" + new Date().getTime() + suffix;
    download(fileName, url);
})

function get_file_suffix(id, idf) {
    let suffix = "";
    $.get({
        url: '/plan/getFileSuffix/' + id + "/" + idf,
        async: false,
        success: function (result) {
            if (result.status === 200) {
                suffix = result.data;
            }
        }
    })
    return suffix;
}

$('#execute-form').form({
    inline: true,
    on: "submit",
    keyboardShortcuts: false,
    fields: {
        "execute-result": {
            identifier: "execute-result",
            rules: [
                {
                    type: "empty",
                    prompt: "请填写执行结果"
                }
            ]
        }
    },
    onSuccess: function () {
        let tar = $('#sub-execute-btn');
        tar.addClass("disabled");
        let val = tar.attr("data-value");
        let url = "/plan/executionConfirmation";
        execute(val, r_e_t, url);
    }
});

function sub_exe_result() {
    $('.ui.modal.execute-modal').modal({
        closable: false
    }).modal("show");
    $('#sub-execute-btn').removeClass("disabled");
}

function execute(val, target, url) {
    let workOrderNumber = $("#workOrderNumber").val();
    let exeResult = $('#execute-result').val();
    if (verify_work_order_number(workOrderNumber)) {
        failure("非法工单")
        return;
    }
    $.get({
        url: url,
        data: {
            "id": val,
            "workOrderNumber": workOrderNumber,
            "exeResult": exeResult
        },
        success: function (result) {
            if (result.status === 200) {
                $('.ui.modal.execute-modal').modal('hide');
                target.parents('td').parent().remove();
                success(result.msg);
                $('#execute-form').form("clear");
            }
        }
    })
}

$(document).on('click', '.sure-plan', function () {
    let val = $(this).parents('td').siblings('.exc-id').text();
    let cur = $(this);
    let url = "/plan/finalConfirmation";
    $('.layui-layer-btn0').removeClass('end');
    layer.confirm('最终确认', {
        btn: ['确定', '取消'],
        icon: 3,
        title: '提示',
        shade: [0.6, '#ffffff', true]
    }, function (index) {
        $('.layui-layer-btn0').addClass('end');
        execute(val, cur, url);
        layer.close(index);
    });
});

function load_finished_exception_info() {
    let workOrderNumber = $("#workOrderNumber").val();
    if (verify_work_order_number(workOrderNumber)) {
        failure("非法工单")
        return;
    }
    $.get({
        url: '/plan/getAllConfirmedExceptionInformation',
        data: {
            "workOrderNumber": workOrderNumber
        },
        success: function (result) {
            if (result.status === 200) {
                package_history_exception_info(result.data, $('#finished-table tbody'))
            }
        }
    })
}

function package_history_exception_info(data, target) {
    if (data.length < 1) {
        let head = $('#finished-table thead');
        target.html("<tr><td colspan='" + head.children().children().length + "'><h2 style='font: italic 2em Georgia, serif;margin: 0 50px;'>no result</h2></td></tr>");
        return;
    }
    target.empty();
    let content;
    $.each(data, function (index, item) {
        content = "<tr>" +
            "<td class='hide identity exc-id'>" + item.id + "</td>" +
            "<td>" + item.serialNumber + "</td>" +
            "<td>" + item.productNumber + "</td>" +
            "<td>" + item.productCode + "</td>" +
            "<td class='accident-details hide'><div style='width: 100px!important;'>" + item.accidentDetails + "</div></td>" +
            "<td>" + item.reporter + "</td>" +
            "<td>" + item.reporterDate + "</td>" +
            "<td class='treatment-details hide'><div style='width: 100px!important;'>" + item.treatmentPlan + "</div></td>" +
            "<td>" + item.closedLoopPeople + "</td>" +
            "<td>" + item.closedLoopPeopleDate + "</td>" +
            "<td>" + item.executor + "</td>" +
            "<td>" + item.executeTime + "</td>" +
            "<td class='execute-details hide'>" + item.executeResult + "</td>" +
            "<td>" + item.confirmor + "</td>" +
            "<td>" + item.confirmorDate + "</td>" +
            "<td>" + item.status + "</td>" +
            "<td class='identity'>" +
            "                <div class='ui dropdown item'>" +
            "                    More" +
            "                    <i class='dropdown icon'></i>" +
            "                    <div class='menu'>" +
            "<a class='item view-result'><i class='chess queen icon'></i>执行结果</a>" +
            "<a class='item view-accident-details'><i class='paw icon'></i>查看异常</a>" +
            "<a class='item view-treatment-plan'><i class='eye icon'></i>查看方案</a>" +
            "                    </div>" +
            "                </div>" +
            "</td>" +
            "</tr>";
        target.append(content);
    });
    $('.ui.dropdown').dropdown({
        on: 'click'
    });
}

$('#export-exception-info').click(function () {
    let table = $("#finished-table");
    if (table.find('tbody').children().length === 0) {
        failure("没有数据可以导出")
        return;
    }
    let workOrderNumber = $('#workOrderNumber').val();
    table.table2excel({
        // 不被导出的表格行的CSS class类
        exclude: ".identity",
        // 导出的Excel文档的名称
        name: "异常工单信息-" + workOrderNumber + "-" + new Date().getTime(),
        // Excel文件的名称
        filename: "异常工单信息-" + workOrderNumber + "-" + new Date().getTime(),
        bootstrap: false
    });
})

//异常信息查询
$('.search-exception').click(function () {
    console.log(flag);
    if (flag) {
        flag = false;
        let searchVal = $('#search-text').val();

        if (/^[\w.]+$/.test(searchVal)) {
            search_exception_info(searchVal);
        } else {
            failure("非法字符");
        }
    }
});

function search_exception_info(val) {
    $.get({
        url: '/plan/exceptionInformationQuery',
        data: {
            "searchValue": val
        },
        success: function (result) {
            if (result.status === 200) {
                package_history_exception_info(result.data, $('#finished-table tbody'));
                flag = true;
            }
        }
    })
}

//刷新
$('#reload-exception-info').click(function () {
    $('#search-text').val('');
    load_finished_exception_info();
});


let websocket = null;

//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
    if ("true" === $('#status').val()) {
        websocket = new WebSocket("ws://localhost:8990/ws");
    }
} else {
    alert('Not support websocket')
}

if (websocket != null) {
    //连接发生错误的回调方法
    websocket.onerror = function () {
        failure("出错啦！");
    };

    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        init_send();
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        processor_data(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {

    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }
}

//处理消息
function processor_data(data) {
    let re = JSON.parse(data);
    switch (re.operation) {
        case "modify":
            handle_Data(re.id, re.val, re.field);
            break;
        case "add":
            add_line(re.id, re.count, re.templateId, re.workOrderNumber);
            break;
        case "del":
            remove_data(re.id, re.count);
            break;
        case "error":
            failure(re.msg);
            temp_tar.text(temp_data);
            break;
        case "other_error":
            failure(re.msg);
            break;
        case "connection":
            connection(re.flag);
            break;
        default:
            failure("操作失败");
    }
}

function connection(flag) {
    if (flag) {
        success("连接成功");
    } else {
        failure("连接失败");
    }
}

function remove_data(tid, count) {
    $('#total').text("已生产" + count + "台");
    let trs = $('#myTable tbody tr:not(:first)');
    let id;
    trs.each(function () {
        id = $(this).children().eq(0).text();
        if (tid === id) {
            $(this).remove();
            return false;
        }
    });
    restore_template();
}

function handle_Data(tid, val, field) {
    let trs = $('#myTable tbody').children().not(':first');
    let id;
    let t_class;
    trs.each(function () {
        id = $(this).children().eq(0).text();
        if (id === tid) {
            t_class = "." + field;
            $(this).find(t_class).text(val);
            return false;
        }
    });
}

//关闭连接
function closeWebSocket() {
    websocket.close();
}

function p_send(message) {
    if (websocket.readyState === WebSocket.CLOSED || websocket.readyState === WebSocket.CLOSING) {
        failure("连接已断开，请检查网络!");
        return;
    }
    message.workOrderNumber = $('#workOrderNumber').val();
    message.templateId = $('#templateId').val();
    message.token = window.localStorage.getItem("Authorization");
    websocket.send(JSON.stringify(message));
}

//发送消息
function send(target) {
    let message = {};
    let data = target.text();
    if (data === temp_data || data.length < 1) {
        return;
    }
    message.id = target.parent().find('.identity').text();
    message.data = data;
    message.field = target.attr('class');
    message.operation = "modify";
    p_send(message);
    temp_field = message.field;
    temp_id = message.id;
}

function add_send() {
    let message = {};
    message.operation = "add";
    p_send(message);
}

function disabled_template() {
    let temp = $('#se-template');
    if (!temp.hasClass('disabled')) {
        temp.addClass('disabled');
    }
}

function restore_template() {
    let temp = $('#se-template');
    if (temp.hasClass('disabled')) {
        temp.removeClass('disabled');
    }
}

function init_send() {
    let message = {};
    message.operation = "connection";
    p_send(message);
}

function r_send() {
    let message = {};
    message.id = $('#myTable tr:last').children().eq(0).text();
    message.operation = "del";
    p_send(message);
}

function getOldData() {
    let templateId = $('#templateId').val();
    let data = "";
    $.get({
        url: '/produce/getSingleData',
        data: {
            "templateId": templateId,
            "field": temp_field,
            "id": temp_id
        },
        async: false,
        beforeSend: function () {
            layer.close(loading);
        },
        success: function (result) {
            if (result.status === 200) {
                data = result.data;
            }
        }
    })
    return data;
}
